<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/18 0018
 * Time: 下午 3:22
 */

namespace app\single\command;


use app\single\model\TableMaxIdModel;
use think\Command;
use think\Db;

class StatXianyu extends Command
{
    protected function execute($input, $output)
    {
        $limit = 10000;
        $maxIdModel = new TableMaxIdModel();
        $maxId = $maxIdModel->getMaxId("stat_xianyu") ?: 0;
        $data = Db::table(config("database.log") . ".log_assets")->alias("le")
            ->leftJoin([config("database.game") . ".role" => "r"], "r.id = le.role_id")
            ->field("le.*, r.pf, r.server_id")
            ->where("item_id", 88)
            ->where("le.id", ">", $maxId)
            ->limit($limit)
            ->select();
        if ($data) {
            $statData = [];
            foreach ($data as $row) {
                $maxId = $row["id"];
                $key = $row["platform"] . "-" . $row["server_id"] . "-" . date("Ymd", $row["time"]) . "-" . $row["role_id"] . "-" . $row["type"] . "-" . $row["origin"];
                if (isset($statData[$key])) {
                    $statData[$key] += $row["update_count"];
                } else {
                    $statData[$key] = $row["update_count"];
                }
            }
            $maxIdModel->updateMaxId("stat_xianyu", $maxId);
            foreach ($statData as $key => $num) {
                list($platform, $serverId, $day, $roleId, $operate, $origin) = explode("-", $key);
                $check = Db::table("c_stat_xianyu")->where("id", $key)->find();
                if ($check) {
                    Db::table("c_stat_xianyu")
                        ->where("id", $key)
                        ->setInc("gold_num", $num);
                } else {
                    $data = [
                        "id" => $key,
                        "day" => $day,
                        "platform" => $platform,
                        "player_id" => $roleId,
                        "operate" => $operate,
                        "origin" => $origin,
                        "gold_num" => $num
                    ];
//                    print_r($data);
                    Db::table("c_stat_xianyu")
                        ->insert($data);
                }
            }
        }
    }
}